package com.chookss.home.publish;


import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;

import androidx.core.app.NotificationCompat;

import com.chookss.R;
import com.chookss.Urls;
import com.chookss.home.entity.NewsEntiry;
import com.chookss.tools.FileUtilss;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UploadNewsService extends Service {

    private ArrayList<Map<String, String>> urlListMaps;
    public static int NotificationId = 2;
    private int numAll = 0;
    private boolean beginUpload = false;//上传中不得重新开始
    private int picNum = 0;
    private List<NewsEntiry> newsEntiryList = new ArrayList<>();

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        initNotification();
    }

    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
        NewsEntiry newsEntiry = (NewsEntiry) intent.getSerializableExtra("newsEntiry");
        if (newsEntiry != null) {
            newsEntiryList.add(newsEntiry);
            if (!beginUpload) {
                urlListMaps = new ArrayList<>(newsEntiryList.get(picNum).getPictures().size());
                beginUpload = true;
                if (newsEntiryList.get(picNum).getPictures().size() > 0) {
                    MyToast.show("正在上传...");
                    getUrlData();
                } else {
                    uploadData();
                }
            }
        }


        return super.onStartCommand(intent, flags, startId);
    }

    private void getUrlData() {
        for (int i = 0; i < newsEntiryList.get(picNum).getPictures().size(); i++) {
            Map<String, String> map = new HashMap<>();
            map.put("picturePath", "");
            map.put("thumbnailPath", "");
            urlListMaps.add(map);
        }
        for (int i = 0; i < newsEntiryList.get(picNum).getPictures().size(); i++) {
            String picUrl = newsEntiryList.get(picNum).getPictures().get(i).getPicturePath();
            File file = new File(picUrl);
            int y = i;
            MyHttpRequest.uploadPicture(Urls.uploadPicture, this, "2", file, new JsonCallback<String>() {
                @Override
                public void onSuccess(Response<String> response) {
                    JSONObject result = null;
                    JSONObject data = null;
                    try {
                        result = new JSONObject(response.body().toString());
                        if (result.getString("code").equals("200")) {
                            data = result.getJSONObject("data");
                            numAll++;
                            Message msg = handler.obtainMessage();
                            msg.arg1 = (numAll * 100) / newsEntiryList.get(picNum).getPictures().size();
                            handler.sendMessage(msg);
                            urlListMaps.get(y).put("picturePath", data.getString("originalUrl"));
                            FileUtilss.delFile(picUrl);
                            if (numAll == newsEntiryList.get(picNum).getPictures().size()) {
                                //图片上传完毕
                                uploadData();
                            }
                        } else if (result.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(result.getString("code"), result.getString("msg"));
                        } else {
                            MyToast.show(result.getString("msg"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        MyToast.show("图片上传失败，请稍后重试");
                        stopSelf();
                    }
                }

                @Override
                public void onError(Response<String> response) {
                    super.onError(response);
                    MyToast.show("图片上传失败，请稍后重试");
                    stopSelf();
                }
            });
        }
    }

    private void uploadData() {
        String newsContent = newsEntiryList.get(picNum).getNewsContent();
        for (int i = 0; i < urlListMaps.size(); i++) {
            newsContent = newsContent + "<img src='" + urlListMaps.get(i).get("picturePath") + "'/>";
        }
        Map<String, Object> map = new HashMap<>();
        map.put("newsTitle", newsEntiryList.get(picNum).getNewsTitle());
        map.put("newsContent", newsContent);
        map.put("newsLocation", newsEntiryList.get(picNum).getNewsLocation());
        map.put("shareFlag", newsEntiryList.get(picNum).getShareFlag());
        map.put("newsPicturesCounts", newsEntiryList.get(picNum).getPictures().size() + "");
        map.put("pictures", XJson.listToJsArrays(urlListMaps));
        map.put("quoteFlag", "0");
        MyHttpRequest.postRequestJson(Urls.addNews, this, XJson.mapToJObj(map).toString(), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        picNum++;
                        if (picNum >= newsEntiryList.size()) {
                            EventBus.getDefault().post(new MyEvent("RefreshNews"));
                            MyToast.show("新闻发布成功");
                            Message msg = handler.obtainMessage();
                            msg.arg1 = 100;
                            handler.sendMessage(msg);
                            stopSelf();
                        } else {
                            numAll = 0;
                            urlListMaps = new ArrayList<>(newsEntiryList.get(picNum).getPictures().size());
                            if (newsEntiryList.get(picNum).getPictures().size() > 0) {
                                getUrlData();
                            } else {
                                uploadData();
                            }
                        }
                    } else {
                        Message msg = handler.obtainMessage();
                        msg.arg1 = 100;
                        handler.sendMessage(msg);
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"),jsonObject.getString("msg"));
                        }else{
                            MyToast.show(jsonObject.getString("msg"));
                        }
                        stopSelf();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    MyToast.show("新闻发布失败，请稍后重试");
                    stopSelf();
                }
            }
        });
    }

    private NotificationManager mNManager;
    private Notification notification;

    private void initNotification() {
        //获得通知消息管理类对象
        mNManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Bitmap largeBitmap = GlideUtils.loadLogo(this);
        notification = new Notification(GlideUtils.loadLogoId(this), "带进条的提醒", System.currentTimeMillis());
//Android8.0以上必须添加 渠道 才能显示通知栏
        RemoteViews contentView = new RemoteViews(getApplication().getPackageName(), R.layout.vedio_upload);
        contentView.setProgressBar(R.id.progressbarUpload, 100, 0, false);
        contentView.setTextViewText(R.id.tvProcess, "已上传" + "0%");
        contentView.setImageViewResource(R.id.appdown_ivLogo, GlideUtils.loadLogoId(this));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //创建渠道
            String id = "news_upload_channel";
            String name = getResources().getString(R.string.app_name);
            NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_LOW);
            mNManager.createNotificationChannel(mChannel);
            //设置图片,通知标题,发送时间,提示方式等属性
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, id);
            int PROGRESS_MAX = 100;
            int PROGRESS_CURRENT = 0;
            builder.setCustomContentView(contentView).setWhen(System.currentTimeMillis())    //系统显示时间
                    .setSmallIcon(GlideUtils.loadLogoId(this))     //收到信息后状态栏显示的小图标
                    .setLargeIcon(largeBitmap)//大图标
                    .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)    //设置默认的三色灯与振动器
                    .setDefaults(Notification.DEFAULT_SOUND)    //设置系统的提示音
                    .setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false)
                    .setAutoCancel(true);       //设置点击后取消Notification
            notification = builder.build();
        } else {
            //设置图片,通知标题,发送时间,提示方式等属性
            Notification.Builder builder = new Notification.Builder(this);
            builder.setContent(contentView).setWhen(System.currentTimeMillis())    //系统显示时间
                    .setSmallIcon(GlideUtils.loadLogoId(this))     //收到信息后状态栏显示的小图标
                    .setLargeIcon(largeBitmap)//大图标
                    .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)    //设置默认的三色灯与振动器
                    .setDefaults(Notification.DEFAULT_SOUND)    //设置系统的提示音
                    .setAutoCancel(true);       //设置点击后取消Notification
            notification = builder.build();
        }
        mNManager.notify(NotificationId, notification);

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            notification.contentView.setProgressBar(R.id.progressbarUpload, 100, msg.arg1,
                    false);
            notification.contentView.setTextViewText(R.id.tvProcess, "已上传"
                    + msg.arg1 + "%");
            mNManager.notify(NotificationId, notification);
            if (msg.arg1 == 100) {
                mNManager.cancel(NotificationId);
            }
            super.handleMessage(msg);
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mNManager != null) {
            mNManager.cancel(NotificationId);
        }
    }
}